package com.softer.chengxin.common.util;


import com.softer.chengxin.common.domin.Common;
import com.softer.chengxin.modify.entity.BaseModifyDetail;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取两个相同对象不同的数据
 *
 * @author Gong Zhiyang
 * @date 2019/4/29
 */
public class GetDifferenceUtil {
    private GetDifferenceUtil() {
    }

    /**
     * 获取两个相同对象不同的数据
     *
     * @param oldObject 旧值
     * @param newObject 新值
     * @return 返回不同数据集合
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static List<BaseModifyDetail> getDifference(Object oldObject, Object newObject) throws IllegalAccessException {
        List<BaseModifyDetail> list = new ArrayList<>();
        Field[] beforeFields = oldObject.getClass().getDeclaredFields();
        Field[] afterFields = newObject.getClass().getDeclaredFields();
        for (int i = 0; i < beforeFields.length; i++) {
            Field beforeField = beforeFields[i];
            Field afterField = afterFields[i];
            beforeField.setAccessible(true);
            afterField.setAccessible(true);
            if (beforeField.get(oldObject) != null) {
                Object oldOb = beforeField.get(oldObject);
                Object newOb = afterField.get(newObject);
                if (oldOb instanceof BigDecimal){
                    if (((BigDecimal) oldOb).compareTo((BigDecimal)newOb)!=0){
                        setValue(list, beforeField.getName());
                    }
                } else if (!oldOb.equals(newOb)) {
                    setValue(list, beforeField.getName());
                }
            } else {
                if (afterField.get(newObject)!=null&&!"".equals(afterField.get(newObject))){
                    setValue(list, beforeField.getName());
                }
            }
        }
        return list;
    }

    private static void setValue(List<BaseModifyDetail> list, String columnName) {
        //获取变更列名的中文名
        BaseModifyDetail baseModifyDetail = new BaseModifyDetail();
        baseModifyDetail.setParam(columnName);
        baseModifyDetail.setValue(Common.ONE);
        list.add(baseModifyDetail);
    }
}
